package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {


    /**
     * spring-data 会自动注入IStrategyCommentRepository实现类
     * <p>
     * IStrategyCommentRepository 接口继承MongoRepository
     * 拥有了 分页,排序,crud基本功能
     * 底层实现 : AOP 操作--动态代理
     */
    @Autowired
    private IStrategyCommentRepository repository;

    //使用较为底层的贾琏欲执事, 实现mongodb操作, 这里用它来实现较为复杂操作
    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyComment comment) {
        repository.save(comment);
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {

        //需要查询评论列表并分页显示,但是目前无法直接得到分页对象page
        //所以只能通过之前高级查询的时候弄pageresult,自己封装page对象
        Query query = new Query();
        if (qo.getDetailId() != -1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查评论总数总数
        long total = template.count(query, StrategyComment.class);


        if (total == 0) {
            return Page.empty();
        }
        //参数1:当前页从0开始  参数2:每页显示的调速 参数3:排序规则 参数4 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        //查当前显示数据
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list, pageable, total);
    }

    @Override
    public void commentThumubUp(String toid, Long userId) {
        //判断当前请求是点赞还是取消点赞
        Optional<StrategyComment> op = repository.findById(toid);
        StrategyComment comment = op.get();
        if (comment == null) {
            return;
        }
        //获取点赞人数,判断点赞人数中包不包括当前用户id
        List<Long> thumbuplist = comment.getThumbuplist();
        if (!thumbuplist.contains(userId)) {
            //如果当前用户不在点赞人数中,name点赞数+1,并且用户id加入点赞用户列表中
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            thumbuplist.add(userId);
        } else {
            //如果是取消点赞,那么点赞数-1,并将用户id移除点赞用户列表
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            thumbuplist.remove(userId);
        }
        //更新
        repository.save(comment);
    }
}
